package com.lynch.adment;

import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.lynch.util.ImageUtil;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * 该类的主要作用是实现图片的异步加载
 * 
 * @author yjc
 */
public class AsyncImageLoader {

	/**
	 * 图片缓存对象
	 * 键是图片的URL，值是一个SoftReference对象，该对象指向一个Drawable对象
	 */ 
	private Map<String, SoftReference<Bitmap>> imageCache;
	public int scaleWidth;
	
	public AsyncImageLoader(int scaleWidth){
		
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
		this.scaleWidth = scaleWidth;
		//System.out.println("宽度好多"+scaleWidth);
	}
	
	/**
	 * 实现图片的异步加载
	 */ 
	public Bitmap loadBitmap(final String imageUrl,
			final GalleryCallback callback) {
		
		/**查询缓存，查看当前需要下载的图片是否已经存在于缓存当中*/ 
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				return softReference.get();
			}
		}

		final Handler handler = new Handler() {
			
			public void handleMessage(Message msg) {
				callback.galleryLoaded((Bitmap) msg.obj);
			}
		};

		/**
		 * 新开辟一个线程，该线程用于进行图片的下载
		 */ 
		new Thread() {
			
			public void run() {
				
				ImageUtil imageUtil = new ImageUtil();
				Bitmap bitmap = loadImageFromUrl(imageUrl,imageUtil);
				imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
				Message message = handler.obtainMessage(0, bitmap);
				handler.sendMessage(message);
			};
		}.start();
		return null;
	}

	/**
	 * 该方法用于根据图片的URL，从网络上下载图片
	 */
	protected Bitmap loadImageFromUrl(String imageUrl,ImageUtil imageUtil) {

		try {
			Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
			Bitmap bitmap = imageUtil.getRoundedCornerBitmap(imageUtil.imageScaleScreen(drawable, scaleWidth), 10);
			return bitmap;
		} catch (Exception e) {
			return null;
		}
	}

}
